package com.atguigu.srb.core.config;

import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.time.Duration;

@Configuration
@EnableCaching
public class RedisConfig {
    @Resource
    RedisTemplate redisTemplate;
    //当前类对象初始化后 给装配的redisTemplate配置键和值的序列化器
    @PostConstruct
    public void init(){
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
    }

    //创建缓存管理器对象添加到容器中
    @Bean
    //只要引入了Commons-pool2依赖 项目启动时会自动初始化redis连接工厂
    public CacheManager cacheManager(LettuceConnectionFactory factory){
        RedisCacheConfiguration config = RedisCacheConfiguration
                .defaultCacheConfig() //设置默认配置
                .entryTtl(Duration.ofMinutes(600)) //设置过期时间
//                .disableCachingNullValues()  设置禁止缓存空值
                .serializeKeysWith(RedisSerializationContext.SerializationPair
                        .fromSerializer(new StringRedisSerializer())) //设置键的序列化器
                .serializeValuesWith(RedisSerializationContext.SerializationPair
                        .fromSerializer(new GenericJackson2JsonRedisSerializer()))//设置值的序列化器
                ;
        //创建缓存管理器对象:
        return RedisCacheManager
                .builder(factory) //配置redis连接工厂
                .cacheDefaults(config) //缓存管理器 管理缓存的配置(键值序列化器、缓存过期时间、空值是否缓存)
            .build();
    }
}
